import type { NextRequest } from "next/server";
import { NextResponse } from "next/server";
import mime from 'mime';
import manager from "../../../../../test/json-serv";
import { IFile } from '@/types';

const DEFAULT_CHUNK_SIZE = 10 * 1024 * 1024; // 10MB

export async function HEAD(request: NextRequest, { params }: { params: { id: string } }) {
    const id = params.id;
    const file = manager.getFileById(id) as IFile;
    if (!file) {
        return new NextResponse('文件未找到', { status: 404 });
    }
    // 返回元数据（无实际内容）
    return new NextResponse(null, {
        headers: {
            'Content-Type': mime.getType(file.extname as string) || 'video/mp4',
            'Content-Length': String(file.size),
            'Accept-Ranges': 'bytes',
            'Access-Control-Allow-Origin': '*',
        },
    });
}

export async function GET(
    request: NextRequest,
    { params }: { params: Promise<{ id: string }> }
) {
    const id = (await params).id;
    const file = manager.getFileById(id) as IFile;

    // 检查文件是否存在
    if (!file) {
        return new NextResponse('文件未找到', { status: 404 });
    }

    // 设置响应头
    const headers = new Headers({
        'Accept-Ranges': 'bytes',
        'Content-Type': mime.getType(file.extname as string) || 'video/mp4',
        'Content-Disposition': `attachment; filename="${encodeURIComponent(file.name)}"`,
        'Access-Control-Allow-Origin': '*',
        'Access-Control-Expose-Headers': 'Content-Range, Content-Length',
    });

    // 处理 Range 请求
    const range = request.headers.get('range');
    if (range) {
        const parts = range.replace(/bytes=/, '').split('-').map(Number);
        // eslint-disable-next-line prefer-const
        let [start, end] = parts;
        end = end || Math.min(start + DEFAULT_CHUNK_SIZE - 1, file.size - 1);

        // 验证范围合法性
        if (
            isNaN(start) || isNaN(end) ||
            start < 0 || end < 0 ||
            start >= file.size || end >= file.size ||
            start > end
        ) {
            headers.set('Content-Range', `bytes */${file.size}`);
            return new NextResponse('无效的字节范围', {
                status: 416,
                headers,
            });
        }

        headers.set('Content-Range', `bytes ${start}-${end}/${file.size}`);
        headers.set('Content-Length', String(end - start + 1));
        return new NextResponse(manager.getFileStream(id, start, end) as ReadableStream, { status: 206, headers });
    } else {
        // 非 Range 请求返回整个文件
        headers.set('Content-Length', String(file.size));
        return new NextResponse(manager.getFileStream(id) as ReadableStream, { status: 200, headers });
    }
}